import Logger from "../../log/Logger";

export interface ISocket {
    connect(url: String):void;
    disConnect():void;
    emit(topic: string, ...args:any[]):void
    listen(topic: string, func:(args:any) => void):void
}

class SocketIO implements ISocket{
    // @ts-ignore
    public socket: SocketIOClient.Socket | undefined;


    connect(url: String): void {
        /*IFTRUE_WEBAPP*/
        const webio = require('socket.io-client');
        this.socket = webio.connect(url+"");
        /*FITRUE_WEBAPP*/

        /*IFTRUE_RNAPP*/
        const rnio = require('socket.io-client');
        this.socket = rnio.connect(url+"", {transports: ['websocket']});
        /*FITRUE_RNAPP*/

        /*IFTRUE_WXAPP*/
        const wxio = require('weapp.socket.io');
        this.socket = wxio.connect(url+"");
        /*FITRUE_WXAPP*/

    }
    disConnect(): void {
        if(this.socket){
            this.socket.disconnect();
        }
    }
    emit(topic: string, ...args: any[]): void {
        if(!this.socket){
            Logger.info(`socket not init yet!`);
            return;
        }
        this.socket.emit(topic, ...args);
    }

    listen(topic: string, func: (args: any) => void): void {
        if(!this.socket){
            Logger.info(`socket not init yet!`);
            return;
        }
        const self = this;
        this.socket.on(topic, function(data:any, resultObjectClz:any, callbackArg:any){
            resultObjectClz = resultObjectClz;
            // only topic = Topic.APP_DOWNSTREAM_MESSAGE, will send a ack to server
            if(callbackArg){
                self.emit('topic.clientack', callbackArg); // 使用 topic.clientack 发送回执.
            }
            func(data);
        });
    }
}

export const socket:ISocket = new SocketIO();

